package com.singleton.loadbalance;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2017/6/5.
 * 负载均衡单例demo
 * 这种模式由于线程安全容易创建很多个实例
 */
public class LoadBalance {
    //私有静态成员变量，存储唯一实例
    private static LoadBalance instance = null;
    //服务器集合
    private List serverList = null;
    //私有构造函数
    private LoadBalance(){
        serverList = new ArrayList();
    }
    //共有静态成员方法。返回唯一实例
    public static LoadBalance getInstance(){
        if(instance == null){
            instance = new LoadBalance();
        }
        return instance;
    }
    //增加服务器
    public void addServer(String server){
        serverList.add(server);
    }
    //删除服务器
    public void removeServer(String server){
        serverList.remove(server);
    }
    //使用random类随机获取服务器
    public String getServer(){
        Random random = new Random();
        int i = random.nextInt(serverList.size());
        return (String)serverList.get(i);
    }
}
